﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Collections;

using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using Gma.System.MouseKeyHook;
using HandyControl.Tools.Extension;
using WWLauncher.Constant;
using WWLauncher.Interface;
using WWLauncher.Model;
using WWLauncher.Tasks;
using WWLauncher.Util;
using WWLauncher.View;
using WWLauncher.View.Other;
using WWLauncher.View.UserControls.Config;
using WWLauncher.ViewModel;
using static System.Threading.Thread;
using static WWLauncher.Util.ShowWindowFollowMouse;
using Window = System.Windows.Window;
using System.Runtime.CompilerServices;

namespace WWLauncher
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    /// 
    public partial class MainWindow : Window, IWindowCommon, IDisposable
    {
        private static readonly MainViewModel ViewModel = MainViewModel.Instance();
        private static readonly AppConfig Config = ViewModel.AppConfig;
        private bool dataFileExist;
        public AutoHidden autoHidden;

        private bool initialize;
        public MainWindow()
        {
            this.DataContext = ViewModel;
            initialize = true;
            InitializeComponent();

            LeftCard.Loaded += (s, e) =>
            {
                if (DesignerProperties.GetIsInDesignMode(this))
                {
                    return;
                }
                LeftCard.ParentWindow = this;
            };
            RightCard.Loaded += (s, e) =>
            {
                if (DesignerProperties.GetIsInDesignMode(this))
                {
                    return;
                }
                RightCard.ParentWindow = this;
                RightCard.process.Window = this;
                RightCard.process.AutoHidden = autoHidden;
            };

        }

        #region window事件
        private void Window_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (initialize && !Config.StartedShowPanel) //第一次启动隐藏窗口
            {
                this.Hide();
            }
            if (initialize && Config.LastPosition)
            {
                this.Left = Config.WindowLeft;
                this.Top = Config.WindowTop;
            }
        }
        private void Window_SourceInitialized(object sender, EventArgs e)
        {
            if (Config.AlwaysTopmost)
            {
                Topmost = Config.AlwaysTopmost;
                WindowUtil.SetTopomost(new WindowInteropHelper(this).Handle);
            }
            //禁用窗口最大化
            WindowUtil.DisableMaxWindow(this);
            Task.Run(() =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {

                    RegisteCloseMonitorHotKey();
                    RegisteCloseRelicCoH2HotKey();
                    //注册热键
                    if (Config.EnableAppHotKey && !Constants.DEV)
                    {
                        RegisterHotKey(true);
                    }
                    if (Config.EnableTodoHotKey && !Constants.DEV)
                    {
                        RegisterCreateToDoHotKey(true);
                    }

                    if (Config.EnableColorPickerHotKey && !Constants.DEV)
                    {
                        RegisterColorPickerHotKey(true);
                    }

                    //注册自启动
                    if (Config.SelfStartUp && !Constants.DEV)
                    {
                        RegisterUtil.SetSelfStarting(Config.SelfStartUp, Constants.AppName);
                    }

                    //注册鼠标监听事件
                    if (Config.MouseMiddleShow && !Constants.DEV)
                    {
                        //注册鼠标监听会导致调试卡顿，如果卡顿时设置一下禁用鼠标中键
                        //new MouseHook().Hook(this);
                        if (Config.MouseMiddleShow)
                        {
                            new UserActivityHook(true, false).OnMouseWheelDown += MainWindow_OnMouseWheelDown;
                        }
                    }

                    //监听实时文件夹菜单
                    FileWatcher.EnableLinkMenuWatcher(ViewModel);


                });
            });
        }
        /// <summary>
        /// 运行开机启动的程序
        /// </summary>
        private void StartupApp()
        {
            //var StartupSeconds = Environment.TickCount / 1000;
            //LogUtil.WriteLog($"StartupSeconds={StartupSeconds}");
            //if (StartupSeconds > 60)//开机60秒以后的就不再执行启动
            //{
            //    return;
            //}

            var list = new List<IconInfo>();
            foreach (var m in ViewModel.MenuList)
            {
                foreach (var i in m.IconList)
                {
                    if (i.IsStartup)
                        list.Add(i);
                }
            }
            list.ForEach(x =>
            {
                new ProcessUtil(this, autoHidden, true).StartIconApp(new IconInfo(x));
            });
        }

        /// <summary>
        /// 窗口加载完毕 执行方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            initialize = false;
            autoHidden = new AutoHidden(this);
            if (Config.MarginHide)
            {
                autoHidden.StartHide();
            }



            Task.Run(() =>
            {
                StartupApp();
                this.Dispatcher.BeginInvoke(() =>
                {
                    BGSettingUtil.BGSetting(this.BGBorder);

                    PowerNotify.Show(Config.EnablePowerManagement);

                    //建立相对路径
                    FileUtil.MakeRelativePath();

                    //设置归属桌面  解决桌面覆盖程序界面的bug
                    WindowUtil.SetOwner(this, WindowUtil.GetDesktopHandle(this, DesktopLayer.Progman));
                    //执行待办提醒
                    ToDoTask.BackLogCheck();
                    Keyboard.Focus(SearchBox);

                    MessageUtil.ChangeWindowMessageFilter(MessageUtil.WM_COPYDATA, 1);

                });
            }).ContinueWith(m =>
            {
                //判断数据文件是否存在 如果不存在那么是第一次打开程序
                dataFileExist = File.Exists(Constants.DataFilePath);
                if (!ViewModel.MenuList.Any())
                {
                    ViewModel.MenuList.Add(new MenuViewModel()
                    {
                        MenuName = "新建菜单",
                        MenuId = System.Guid.NewGuid().ToString(),
                        MenuEdit = Visibility.Collapsed
                    });
                }

                this.Dispatcher.BeginInvoke(() =>
                {
                    if (!dataFileExist)
                    {
                        Guide();
                    }
                });
            });


        }

        internal MonitorWindow Monitor { get; set; }

        /// <summary>
        /// 显示监控界面
        /// </summary>
        internal void DisplayMonitor()
        {
            if (Config.IsMonitor)
            {
                if (Monitor == null)
                    Monitor = new MonitorWindow();
                Monitor.Show();
            }
            else
            {
                Monitor?.Close();
                Monitor = null;
            }
        }

        private void Window_Deactivated(object sender, EventArgs e)
        {
            AppWindowLostFocus();
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (Config.LastPosition)
            {
                Config.WindowTop = this.Top;
                Config.WindowLeft = this.Left;
            }
            autoHidden.WindowClosing = true;
            autoHidden.StopHide();
            ConfigUtil.SaveAppData();
            Monitor?.Close();

            RegisterUtil.ExportReg(Constants.AppDir + @"\data\Desktop.reg", @"HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Bags\1\Desktop");
            Dispose();
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (guideRun)
            {
                Guide();
            }
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            SearchBox.Focus();
        }

        /// <summary>
        /// 鼠标进入后 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_MouseEnter(object sender, MouseEventArgs e)
        {
            //防止延迟贴边隐藏
            if (!RunTimeStatus.WpfWindowOpening)
                autoHidden.MarginHideAndOtherShow = false;
        }

        public void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            //char c = (char)e.Key;

            if (e.Key == Key.Escape)
            {
                HideApp();
            }

            if (RunTimeStatus.SearchBoxShow && (e.Key == Key.Up
                                                || e.Key == Key.Down
                                                || e.Key == Key.Tab
                                                || e.Key == Key.Enter
                ))
            {
                if (e.Key == Key.Down || e.Key == Key.Tab)
                {
                    SearchResControl res = RightCard.VerticalCard.Content as SearchResControl;
                    res.SearchListBoxIndexAdd();
                }
                else if (e.Key == Key.Up)
                {
                    SearchResControl res = RightCard.VerticalCard.Content as SearchResControl;
                    res.SearchListBoxIndexSub();
                }
                else if (e.Key == Key.Enter)
                {
                    SearchResControl res = RightCard.VerticalCard.Content as SearchResControl;
                    res.StartupSelectionItem();
                }
            }
        }


        #endregion



        /// <summary>
        /// 程序窗体拖拽
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DragMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        /// <summary>
        /// 关闭按钮单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            HideApp();
        }

        /// <summary>
        /// 右键任务栏图标 显示主面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void DisplayApp_Click(object sender, RoutedEventArgs e)
        {
            DisplayApp();
        }
        public void DisplayApp()
        {
            if (autoHidden.OnHide)
            {
                //修改贴边隐藏状态为未隐藏
                autoHidden.IsHide = false;

                if (this.Left <= 0)
                {
                    this.Left = 0;
                    Config.WindowLeft = 0;
                }
                if (this.Top <= 0)
                {
                    this.Top = 0;
                    Config.WindowTop = 0;
                }
                this.Show();
                //if (!MouseUtil.MouseInWindow(this))
                //{
                //    autoHidden.WaitHide(3000, () =>
                //    {
                //        autoHidden.MarginHideAndOtherShow = true;
                //    });
                //}
                autoHidden.MarginHideAndOtherShow = true;
            }

            if (Config.FollowMouse)
            {
                ShowWindowFollowMouse.Display(this, MousePosition.Center, 0, 0);
            }


            this.Activate();
            this.Show();
            Monitor?.Activate();

            //if (Config.AppAnimation)
            //{
            //    Config.IsShow = true;
            //}
            //else
            //{
            //    Config.IsShow = null;
            //    //防止永远不显示界面
            //    if (this.Opacity < 1)
            //    {
            //        this.Opacity = 1;
            //    }
            //}


            FadeStoryBoard(1, Constants.WindowAnimationTime, Visibility.Visible);

            Keyboard.Focus(this);
            if (RunTimeStatus.ShowMenuPasswordbox)
            {
                this.RightCard.PDDialog.SetFocus();
            }
            else
            {
                Keyboard.Focus(this.SearchBox);
            }
            if (!this.IsVisible)
            {
                LogUtil.WriteLog("窗口还在隐藏");
            }
        }

        public void HideApp()
        {
            HideAppVis();
            //if (Config.AppAnimation)
            //{
            //    Config.IsShow = false;
            //}
            //else
            //{
            //    Config.IsShow = null;
            //    HideAppVis();
            //}

        }

        private void HideAppVis()
        {
            //关闭锁定
            RunTimeStatus.LockAppPanel = false;
            if (RunTimeStatus.SearchBoxShow)
            {
                this.HidedSearchBox();
            }
            this.Hide();

        }

        /// <summary>
        /// 淡入淡出效果
        /// </summary>
        /// <param name="opacity"></param>
        /// <param name="milliseconds"></param>
        /// <param name="visibility"></param>
        public void FadeStoryBoard(int opacity, int milliseconds, Visibility visibility)
        {
            if (Config.AppAnimation)
            {
                DoubleAnimation opacityAnimation = new DoubleAnimation
                {
                    From = this.Opacity,
                    To = opacity,
                    Duration = new Duration(TimeSpan.FromMilliseconds(milliseconds))
                };
                opacityAnimation.Completed += (s, e) =>
                {
                    this.BeginAnimation(OpacityProperty, null);
                    if (visibility == Visibility.Visible)
                    {
                        this.Opacity = 1;
                    }
                    else
                    {
                        this.Opacity = 0;
                        CommonCode.SortIconList();
                    }
                };
                Timeline.SetDesiredFrameRate(opacityAnimation, 60);
                this.BeginAnimation(OpacityProperty, opacityAnimation);
            }
            else
            {
                //防止关闭动画后 窗体仍是0透明度
                this.Opacity = 1;
                this.Visibility = visibility;
                if (visibility == Visibility.Collapsed)
                {
                    CommonCode.SortIconList();
                }
            }
        }




        /// <summary>
        /// 单击系统托盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NotifyIcon_Click(object sender, RoutedEventArgs e)
        {
            if (CheckShouldShowApp())
            {
                DisplayApp();
            }
            else
            {
                HideApp();
            }
        }

        private bool CheckShouldShowApp()
        {
            return this.Visibility == Visibility.Collapsed || this.Visibility == Visibility.Hidden
                || this.Opacity == 0
                || autoHidden.IsHide
                || !WindowUtil.WindowIsTop(this);
        }

        /// <summary>
        /// 右键任务栏图标 设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfigApp_Click(object sender, RoutedEventArgs e)
        {
            new ConfigWindow(ViewModel.AppConfig, this).Show();
        }

        #region 右键任务栏图标打开程序目录
        /// <summary>
        /// 右键任务栏图标打开程序目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenThisDir_Click(object sender, RoutedEventArgs e)
        {
            Process p = new Process();
            p.StartInfo.FileName = "Explorer.exe";
            p.StartInfo.Arguments = "/e,/select," + Constants.AppDir + Constants.AppName + ".exe";
            p.Start();
        }
        #endregion



        /// <summary>
        /// 设置图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfigButton_Click(object sender, RoutedEventArgs e)
        {
            SettingMenus.IsOpen = true;
        }

        /// <summary>
        /// 设置菜单点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfigMenu_Click(object sender, RoutedEventArgs e)
        {
            new ConfigWindow(ViewModel.AppConfig, this).Show();
        }
        /// <summary>
        /// 待办任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BacklogMenu_Click(object sender, RoutedEventArgs e)
        {
            new ToDoWindow().Show();
        }
        /// <summary>
        /// 禁用设置按钮右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SettingButton_Initialized(object sender, EventArgs e)
        {
            SettingButton.ContextMenu = null;
        }


        private void AppWindowLostFocus()
        {
            if (Config.AppHideType == AppHideType.LostFocus
                && this.Opacity == 1 && !RunTimeStatus.LockAppPanel)
            {
                //如果开启了贴边隐藏 则窗体不贴边才隐藏窗口
                if (!Config.MarginHide || (Config.MarginHide && !autoHidden.IsHide))
                {
                    HideApp();
                }
            }
        }

        /// <summary>
        /// 右键任务栏图标退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExitApp_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
        /// <summary>
        /// 重启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReStartApp_Click(object sender, RoutedEventArgs e)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.UseShellExecute = true;
            startInfo.FileName = Constants.AppExe;
            startInfo.WorkingDirectory = Constants.AppDir;
            startInfo.Arguments = "-restart";
            var proc = new Process();
            proc.StartInfo = startInfo;
            proc.Start();
            Application.Current.Shutdown();
        }

        /// <summary>
        /// 关闭托盘图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CloseBarIcon_Click(object sender, RoutedEventArgs e)
        {
            Config.ShowBarIcon = false;
        }


        /// <summary>
        /// 打开屏幕拾色器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ColorPicker_Click(object sender, RoutedEventArgs e)
        {
            TaskbarContextMenu.IsOpen = false;
            GlobalColorPickerWindow.CreateNoShow();
        }

        private void Window_GotFocus(object sender, RoutedEventArgs e)
        {
            // 如果没有在修改菜单 并且不是右键点击了面板
            if (!RunTimeStatus.IsMenuEdit
                && !RunTimeStatus.ShowRightBtnMenu
                && !RunTimeStatus.AppBtnIsDown)
            {
                if (RunTimeStatus.ShowMenuPasswordbox)
                {
                    //必须在其它文本框没有工作的时候才给密码框焦点
                    RightCard.PDDialog.SetFocus();
                }
                else
                {
                    //必须在其它文本框没有工作的时候才给搜索框焦点
                    Keyboard.Focus(SearchBox);
                }

            }

        }


        /// <summary>
        /// 备份数据文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BakDataFile_Click(object sender, RoutedEventArgs e)
        {
            await Task.Run(() =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    ConfigUtil.BakAppData(this);
                });
            });
        }

        private void AppButton_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //点击了面板
            RunTimeStatus.AppBtnIsDown = true;
            new Thread(() =>
            {
                Sleep(50);
                RunTimeStatus.AppBtnIsDown = false;
            }).Start();
        }


        private ICommand hideCommand;
        public ICommand HideCommand
        {
            get
            {
                return hideCommand ??= new RelayCommand(
                    p => true,
                    p => { HideAppVis(); });
            }
        }
        [DebuggerStepThrough]
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
            if (hwndSource != null)
            {
                IntPtr handle = hwndSource.Handle;
                hwndSource.AddHook(new HwndSourceHook(WndProc));
            }
        }
        [DebuggerStepThrough]
        IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == MessageUtil.WM_COPYDATA)
            {
                MessageUtil.CopyDataStruct cds = (MessageUtil.CopyDataStruct)Marshal.PtrToStructure(lParam, typeof(MessageUtil.CopyDataStruct))!;
                if ("DisplayApp".Equals(cds.msg))
                {
                    DisplayApp();
                }
            }
            return hwnd;
        }

        #region 新手引导

        private int guideIndex = 0;
        private bool guideRun = false;

        private void Guide()
        {
            try
            {
                guideRun = true;
                //防止影响主程序进程
                if (CheckShouldShowApp())
                {
                    DisplayApp();
                }
                GrayBorder.Visibility = Visibility.Visible;
                GuideSwitch(guideIndex);
                GuideCard.Visibility = Visibility.Visible;
            }
            catch (Exception) { guideRun = false; }
        }

        private void GuideSwitch(int index)
        {
            guideIndex = index;
            GuideNum.Text = Convert.ToString(index + 1);
            GuideTitle1.Text = GuideListModel.mainWindowGuideList[index].Title1;
            GuideTitle2.Text = GuideListModel.mainWindowGuideList[index].Title2;
            GuideText.Text = GuideListModel.mainWindowGuideList[index].GuideText;

            if (index == 0)
            {
                PreviewGuideBtn.Visibility = Visibility.Collapsed;
                NextGuideBtn.Content = "下一步";
            }
            else if (index > 0 && index < GuideListModel.mainWindowGuideList.Count - 1)
            {
                PreviewGuideBtn.Visibility = Visibility.Visible;
                NextGuideBtn.Content = "下一步";
            }
            else
            {
                NextGuideBtn.Content = "完成";
            }

            switch (index)
            {
                default: //0  //右侧列表区域

                    Point point = RightCard.TransformToAncestor(this).Transform(new Point(0, 0));
                    //内部中上
                    GrayBoderClip(point.X, point.Y, RightCard.ActualWidth, RightCard.ActualHeight,
                        new Thickness(point.X, point.Y, 0, 0));
                    break;
                case 1:  //左侧菜单
                    Point leftCardPoint = LeftCard.TransformToAncestor(this).Transform(new Point(0, 0));
                    GrayBoderClip(leftCardPoint.X, leftCardPoint.Y, LeftCard.ActualWidth, LeftCard.ActualHeight,
                        // 外部中下侧
                        new Thickness(leftCardPoint.X + LeftCard.ActualWidth,
                        leftCardPoint.Y + LeftCard.ActualHeight / 2 - GuideCard.ActualHeight / 2, 0, 0));
                    break;
                case 2: //头部拖拽栏
                    GrayBoderClip(0, 0, this.Width, 56,
                        // 外部中下侧
                        new Thickness(this.Width / 2 - GuideCard.ActualWidth / 2, 56, 0, 0));
                    break;
                case 3:
                    Point mainBtnPoint = MainBtnPanel.TransformToAncestor(this).Transform(new Point(0, 0));
                    GrayBoderClip(mainBtnPoint.X, mainBtnPoint.Y - 6, MainBtnPanel.ActualWidth, MainBtnPanel.ActualHeight + 8,
                        // 外部左下侧
                        new Thickness(mainBtnPoint.X - GuideCard.Width,
                        mainBtnPoint.Y, 0, 0));
                    break;
            }
        }


        private void GrayBoderClip(double x, double y, double w, double h, Thickness margin)
        {
            PathGeometry borGeometry = new PathGeometry();

            RectangleGeometry rg = new RectangleGeometry
            {
                Rect = new Rect(0, 0, this.Width, this.Height)
            };
            borGeometry = Geometry.Combine(borGeometry, rg, GeometryCombineMode.Union, null);
            GrayBorder.Clip = borGeometry;

            RectangleGeometry rg1 = new RectangleGeometry
            {
                Rect = new Rect(x, y, w, h)
            };
            borGeometry = Geometry.Combine(borGeometry, rg1, GeometryCombineMode.Exclude, null);
            GuideCard.Margin = margin;
            GrayBorder.Clip = borGeometry;
        }

        private void PreviewGuideBtn_Click(object sender, RoutedEventArgs e)
        {
            int index = Convert.ToInt32(GuideNum.Text) - 1;
            int previewIndex = index - 1;
            GuideSwitch(previewIndex);
        }

        private void NextGuideBtn_Click(object sender, RoutedEventArgs e)
        {
            if ("完成".Equals(NextGuideBtn.Content.ToString()))
            {
                GrayBorder.Visibility = Visibility.Collapsed;
                GuideCard.Visibility = Visibility.Collapsed;
                guideIndex = 0;
                guideRun = false;
                return;
            }
            int index = Convert.ToInt32(GuideNum.Text) - 1;
            int nextIndex = index + 1;
            GuideSwitch(nextIndex);
        }


        #endregion

        private void Guide_Click(object sender, RoutedEventArgs e)
        {
            Guide();
        }

        private void MenuItem_Checked(object sender, RoutedEventArgs e)
        {
            DisplayMonitor();
        }


        private void WorkingButton_MouseEnter(object sender, MouseEventArgs e)
        {
            var button = (Button)sender;
            button.Background = Brushes.White;
        }

        private void WorkingButton_MouseLeave(object sender, MouseEventArgs e)
        {
            var button = (Button)sender;
            button.Background = Brushes.Transparent;
        }
        PowerWindow power;
        private void PowerNotify_Click(object sender, RoutedEventArgs e)
        {
            power ??= new PowerWindow();

            power?.ToggleWindowVisibility();
        }
        private void PowerContextMenu_Click(object sender, RoutedEventArgs e)
        {
            throw new NotImplementedException();
        }
        private void Upgrade_Click(object sender, RoutedEventArgs e)
        {
            Process p = new Process();
            p.StartInfo.FileName = "Upgrade.exe";
            p.StartInfo.Arguments = "";
            p.Start();
        }
        private void About_Click(object sender, RoutedEventArgs e)
        {
            new ConfigWindow(ViewModel.AppConfig, this, 0).Show();
        }
        public void Dispose()
        {
            threadStopFlg = true;
            autoHidden?.Dispose();
        }
        private void SaveConfig_Click(object sender, RoutedEventArgs e)
        {
            ConfigUtil.SaveAppData();
        }

        private void ReclaimMemory_Click(object sender, RoutedEventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.SuppressFinalize(this);
        }

        private void Window_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            RunTimeStatus.WpfWindowOpening = true;
        }

        private void Window_ContextMenuClosing(object sender, ContextMenuEventArgs e)
        {
            if (RunTimeStatus.WpfWindowClick)
            {
                RunTimeStatus.WpfWindowClick = false;
            }
            else
            {
                RunTimeStatus.WpfWindowOpening = false;
            }
        }
    }
}